'use strict';

const fs = require('fs');
const path = require('path');

var Util = {
    _isRemoveBg: true,
    bgColor: null,
    tolerance: 0,
    parseGif: function (gifFile, tmpDir, callback) {
        const gifImg = document.createElement('img');
        gifImg.setAttribute('rel:animated_src', URL.createObjectURL(gifFile));
        gifImg.setAttribute('rel:auto_play', '0');
        // Modified pictures must be added to the body
        document.body.appendChild(gifImg);
        // Construction example
        const SuperGif = Editor.require('packages://gif-to-animation/utils/libgif.js');
        var rub = new SuperGif({ gif: gifImg });
        rub.load((gif) => {
            let dalayTime = rub.get_delay();
            var img_list = [];
            var gif_name = gifFile.name.replace('.gif', '');
            for (let i=0; i <= rub.get_length(); i++) {
                // Traversing through each frame of a GIF instance
                rub.move_to(i);
                // Converting each frame of canvas into a file object
                let filename = gif_name + `-${i}` + '.png';
                let fullFileName = path.join(tmpDir, filename);
                this.convertCanvasToImage(rub.get_canvas(), fullFileName);
                let item = {};
                item.fullpath = fullFileName;
                item.name = filename;
                img_list.push(item);

            }
            callback(null, gif_name, dalayTime, img_list);
        });
    },

    savePngFile (dataurl, fullFileName) {
        const arr = dataurl.split(',');
        // const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        var n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        fs.writeFileSync(fullFileName, u8arr, 'utf8');
    },

    /**清除图片背景颜色 **/
    saveRmoveBgPngFile: function (canvas, fullFileName) {
        //背景颜色  白色
        const rgba = [255, 255, 255, 255];
        if (this.bgColor.length >= 3) {
            for (let i = 0; i < 3; i++) {
                rgba[i] = parseInt(this.bgColor[i]);
                if (rgba[i] < 0) {
                    rgba[i] = 0;
                }
                if (rgba[i] > 255) {
                    rgba[i] = 255;
                }
            }
        }
        // 容差大小
        const tolerance = this.tolerance;

        var imgData = null;
        const [r0, g0, b0, a0] = rgba;
        var r, g, b, a;
        const context = canvas.getContext('2d');

        imgData = context.getImageData(0, 0, canvas.width, canvas.height);

        for (let i = 0; i < imgData.data.length; i += 4) {
            r = imgData.data[i];
            g = imgData.data[i + 1];
            b = imgData.data[i + 2];
            a = imgData.data[i + 3];
            const t = Math.sqrt((r - r0) ** 2 + (g - g0) ** 2 + (b - b0) ** 2 + (a - a0) ** 2);
            if (t <= tolerance) {
                imgData.data[i] = 0;
                imgData.data[i + 1] = 0;
                imgData.data[i + 2] = 0;
                imgData.data[i + 3] = 0;
            }
        }
        context.putImageData(imgData, 0, 0);
        this.savePngFile(canvas.toDataURL('image/png'), fullFileName);
    },

    convertCanvasToImage (canvas, fullFileName) {
        if (this._isRemoveBg) {
            this.saveRmoveBgPngFile(canvas, fullFileName);
        } else {
            this.savePngFile(canvas.toDataURL('image/png'), fullFileName);
        }

    },

    doWork () {
        var templatePrefabUrl = Editor.url('packages://test-prefab/template');
        var destUrl = Editor.url('db://assets/resources');
        Editor.log("templatePrefabUrl:" + templatePrefabUrl);
        Editor.log("destUrl:" + destUrl);

        if (fs.existsSync(destUrl) === false) {
            fs.mkdirSync(destUrl);
        }
        // fs.copyFile(templatePrefabUrl, destUrl, (err) => {
        //     if (err) throw err;
        //     Editor.log('源文件已拷贝到目标文件');
        // });
        let self = this;
        Editor.assetdb.import([templatePrefabUrl], 'db://assets/resources', true, function ( err, results ) {
            self.loadPrefabToScene();
        });
    },

    loadPrefabToScene () {
        var url = 'db://assets/resources/template/EmptyPrefab.prefab';
        Editor.assetdb.queryUuidByUrl(url, function (error, uuid) {
            this.loadPrefabByUuid(uuid);
        }.bind(this));
        // let self = this;
        // _Scene.loadSceneByUuid(uuid, function(error) {
        //     //do more work
        //     if (error) {
        //         Editor.log(error);
        //     } else {
        //         self.onLoadPrefabFinish();
        //     }
        // });
    },

    loadPrefabByUuid (uuid) {
        this._loadUuid = uuid;
        Editor.Ipc.sendToAll('scene:enter-prefab-edit-mode', uuid);
    },
    enterPrefabEditModeCallback (uuid) {
        if (this._loadUuid !== uuid) {
            Editor.log('enterPrefabEditModeCallback this._loadUuid !== uuid :' + uuid);
            return;
        }

        // Editor.Scene.callSceneScript('test-prefab', 'load-scene-by-uuid', uuid, function (err, length) {
        //     console.log(`get-canvas-children callback : length - ${length}`);
        // }, 100000);
        // Editor.Ipc.sendToMain('test-prefab:load-scene-by-uuid', uuid, function (error, msg) {
        //     this.loadSceneCallback(error, msg);
        // }.bind(this), 1000);

    },

    loadSceneCallback (error, msg) {
        if (error) {
            Editor.log(error);
        } else {
            Editor.log("msg" + msg);
        }
    },

    onLoadPrefabFinish: function () {
        Editor.log('onLoadPrefabFinish');
    },

    doOther () {
        Editor.Scene.callSceneScript('test-prefab', 'get-canvas-children', function (err, length) {
            console.log(`get-canvas-children callback : length - ${length}`);
        });
    },

};
module.exports = Util;